package offer.offer03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 100, 100 找规律, 特别无聊
 * 先把每一位的基础增量确定
 * 然后从高到低, 确定每一位上具体的数所带来的增益
 */
public class Solution43 {
    public int countDigitOne(int n) {
        if(n==0) return 0;
        //按顺序存储每一位数
        List<Integer> numList = new ArrayList<>();
        while(n != 0){
            numList.add(n % 10);
            n /= 10;
        }
        System.out.println(numList);


        int numberLen = numList.size();
        //存储每一位为最高位时应有的1的数量
        int[] baseCacu = new int[numberLen];
        baseCacu[0] = 1;
        for(int i = 1; i < numberLen; i ++){
            baseCacu[i] = 10 * (baseCacu[i-1] - 1) + (int)Math.pow(10, i - 1) + 1;
        }
        System.out.println(Arrays.toString(baseCacu));

        int sumof1 = 0;
        int oneBefore = 0;//统计当前位之前有几个1, 比如121345, 则百位前有2个1
        for(int i = numberLen - 1; i >= 0; i --){
            int curNum = numList.get(i);
            if(curNum == 1){
                sumof1 += oneBefore * (int)Math.pow(10, i)
                        + baseCacu[i];
                oneBefore ++ ;
            }else {
                if(curNum == 0) continue;
                sumof1 += oneBefore * (int)Math.pow(10, i)*curNum
                        + (baseCacu[i] - 1) * curNum + (int)Math.pow(10, i);
            }
        }
        return sumof1;
    }

    /**
     * 骚到我不敢说话
     */
    public int countDigitOne2(int n) {
        int digit = 1, res = 0;
        int high = n / 10, cur = n % 10, low = 0;
        while(high != 0 || cur != 0) {
            if(cur == 0) res += high * digit;
            else if(cur == 1) res += high * digit + low + 1;
            else res += (high + 1) * digit;
            low += cur * digit;
            cur = high % 10;
            high /= 10;
            digit *= 10;
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(new Solution43().countDigitOne(100));
    }
}
